package com.changgou.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.changgou.entity.Page;
import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;

/**
 * 商品搜索控制器
 * 
 * @author gaofeng
 * @date 2025年04月27日 18:44
 */
@Controller
@CrossOrigin
@RequestMapping("/search")
public class SkuController {
    @Resource
    private SkuFeign skuFeign;

    @RequestMapping("/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        Map<String, Object> result = skuFeign.search(searchMap);
        model.addAttribute("result", result);
        model.addAttribute("searchMap", searchMap);

        Page<SkuInfo> skuInfoPage = new Page<>(Long.parseLong(result.get("total").toString()),
            Integer.parseInt(result.get("pageNumber").toString()) + 1,
            Integer.parseInt(result.get("pageSize").toString()));
        model.addAttribute("page", skuInfoPage);

        List<String> urls = buildCustomUrl(searchMap);
        model.addAttribute("url", urls.get(0));
        model.addAttribute("sortUrl", urls.get(1));
        return "search";
    }

    private List<String> buildCustomUrl(Map<String, String> searchMap) {
        List<String> urls = new ArrayList<>(2);
        StringBuilder url = new StringBuilder();
        StringBuilder sortUrl = new StringBuilder();
        url.append("/search/list");
        sortUrl.append("/search/list");
        url.append("?");
        sortUrl.append("?");
        for (String key : searchMap.keySet()) {
            if ("pageNum".equals(key) || "pageSize".equals(key)) {
                continue;
            }

            url.append(key).append("=").append(searchMap.get(key)).append("&");

            if ("sortField".equals(key) || "sortRule".equals(key)) {
                continue;
            }

            sortUrl.append(key).append("=").append(searchMap.get(key)).append("&");
        }

        urls.add(url.substring(0, url.length() - 1));
        urls.add(sortUrl.substring(0, sortUrl.length() - 1));
        return urls;
    }
}
